import { topicApi } from '/api/topic'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { $event } from '/utils'
import { getServer } from '/store/mutations'

Component({
  properties: {
    topic: { type: Object, value: {} as DomoTopic },
  },
  data: {
    access: {},
    mineId: Number,
  },
  lifetimes: {
    attached() {
      this.setData({ access: GlobalData.access })
      const token = wx.getStorageSync(`${getServer()}/accessToken`).data
      if (token) {
        this.getUserId()
      }
    },
  },
  methods: {
    async onFollowTopic(e: WechatMiniprogram.CustomEvent) {
      await checkAuth()
      const mineId = this.getUserId()
      if (+mineId === +e.currentTarget.dataset.id) return
      if (this.data.topic.has_followed) {
        await topicApi.unfollowTopic(this.data.topic.id)
      } else {
        await topicApi.followTopic(this.data.topic.id)
      }
      this.setData({
        'topic.has_followed': !this.data.topic.has_followed,
      })
    },
    async onReward(e: WechatMiniprogram.CustomEvent) {
      await checkAuth()
      const mineId = this.getUserId()
      if (+mineId === +e.currentTarget.dataset.id) {
        wx.showToast({
          title: '不能打赏自己',
          icon: 'none',
        })
        return
      }
      if (!GlobalData.access.reward) {
        wx.showToast({
          title: '打赏功能已关闭',
          icon: 'none',
        })
        return
      }
      $event.emit('reward', { topicId: this.data.topic.id })
    },
    toTopic(e: WechatMiniprogram.BaseEvent) {
      const id = e.currentTarget.dataset.id
      wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${id}` })
    },
    getUserId() {
      const server = getServer()
      const user = wx.getStorageSync(`${server}/logged`).data
      this.setData({
        mineId: user.id,
      })
      return user.id
    },
  },
})
